package cn.com.scooper.impl.netty;

import cn.com.scooper.service.ks.MessageCallback;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;

@Slf4j
public class ClientHandler extends ChannelInboundHandlerAdapter {

    private MessageCallback messageCallback;

    private ReportNettyClient reportNettyClient;

    public ClientHandler(MessageCallback messageCallback, ReportNettyClient reportNettyClient){
        this.messageCallback = messageCallback;
        this.reportNettyClient = reportNettyClient;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("【向市局上报数据->netty连接可用】");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("【向市局上报数据->netty连接断开】尝试重连");
        reportNettyClient.doConnect();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        String buf = readMsg(msg);
        log.info("【向市局上报数据->服务器响应】响应数据内容：{}",buf);
        // 接收到消息后调用回调函数处理
        if (messageCallback != null) {
            messageCallback.onMessageReceived(buf);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
        log.error("【向市局上报数据->服务器连接异常】异常原因：{}",cause.getMessage());
        cause.printStackTrace();
    }

    /**
     * {"success":true,"dataId":"c6314bc9888b4134bc9e6b989dd37679"}@@
     * {"success":false,"dataId":"c6314bc9888b4134bc9e6b989dd37679","error":{"code":"400","id":"c6314bc9888b4134bc9e6b989dd37679","message":"未授权的访问"}}@@
     *
     * @param msg
     * @return
     */
    private String readMsg(Object msg){
        String body = null;
        try {
            ByteBuf buf = (ByteBuf) msg;
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            body = new String(req, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return body;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleStateEvent.READER_IDLE_STATE_EVENT.state()) {
                log.info("【向市局上报数据->netty连接心跳检测】没有收到服务器的心跳响应，重连");
                ctx.close();
            } else if (event.state() == IdleStateEvent.WRITER_IDLE_STATE_EVENT.state()) {
                log.info("【向市局上报数据->netty连接心跳检测】发送心跳到服务器");
                // 发送心跳消息到服务器
                ByteBuf buf = Unpooled.copiedBuffer("ping".getBytes());
                ctx.writeAndFlush(buf);
            }
        }

        super.userEventTriggered(ctx, evt);
    }

}
